package es.udc.fbellas.j2ee.tiendaweb.model.usuariofacade.plain.actions;

import java.sql.Connection;

import es.udc.fbellas.j2ee.util.exceptions.InternalErrorException;
import es.udc.fbellas.j2ee.util.exceptions.InstanceNotFoundException;
import es.udc.fbellas.j2ee.util.sql.TransactionalPlainAction;
import es.udc.fbellas.j2ee.tiendaweb.model.usuario.TO.UsuarioProfileTO;
import es.udc.fbellas.j2ee.tiendaweb.model.usuario.DAO.SQLUsuarioProfileDAO;
import es.udc.fbellas.j2ee.tiendaweb.model.usuario.DAO.SQLUsuarioProfileDAOFactory;
import es.udc.fbellas.j2ee.tiendaweb.model.usuariofacade.util.PasswordEncrypter;
import es.udc.fbellas.j2ee.tiendaweb.model.usuariofacade.exceptions.IncorrectPasswordException;

public class CambiarPasswordAction implements TransactionalPlainAction {

    private String loginName;
    private String oldClearPassword;
    private String newClearPassword;

    public CambiarPasswordAction(String loginName, String oldClearPassword,
        String newClearPassword) {
        
        this.loginName = loginName;
        this.oldClearPassword = oldClearPassword;
        this.newClearPassword = newClearPassword;
            
    }

    /**
     *
     * @return <code>null</code>
     */
    public Object execute(Connection connection) 
        throws InstanceNotFoundException, IncorrectPasswordException,
        InternalErrorException {
                
        SQLUsuarioProfileDAO usuarioProfileDAO = SQLUsuarioProfileDAOFactory.getDAO();
        UsuarioProfileTO usuarioProfileTO = usuarioProfileDAO.find(connection, 
            loginName);
        String storedPassword = usuarioProfileTO.getEncryptedPassword();
            
        if (!PasswordEncrypter.isClearPasswordCorrect(oldClearPassword,
            storedPassword)) {
            throw new IncorrectPasswordException(loginName);
        }

        usuarioProfileTO.setEncryptedPassword(
            PasswordEncrypter.crypt(newClearPassword));
        usuarioProfileDAO.update(connection, usuarioProfileTO);

        return null;            

    }
    
    /* 
     * This class is tested by
     * "es.udc.fbellas.j2ee.miniportal.model.userfacade.delegate.
     * UserFacadeDelegateFactory".
     */    

}
